/*
 *
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package relaibluetooth;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.microedition.io.StreamConnection;

/**
 *
 * @author Etienne
 */
public class threadConnection implements Runnable{
private InputStream m_Input=null;
private OutputStream m_Output=null;
private StreamConnection m_StrmConn = null;
private relai relai;

byte[] data = null;



public threadConnection(StreamConnection m_StreamConnection,relai relai) {
        this.m_StrmConn=m_StreamConnection;
        this.relai=relai;

//récupération des input et output stream
        try {
            m_Output = m_StrmConn.openOutputStream();
             m_Input = m_StrmConn.openInputStream();
        } catch (IOException ex) {
            Logger.getLogger(threadConnection.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void run() {
       boolean connect = false;
        try {

            //récupération du mot de passe envoyé par le téléphone
            int mdp = m_Input.read();
            //vérification du mot de passe
            connect=relai.acceptConnection(mdp);

        } catch (IOException ex) {
            Logger.getLogger(threadConnection.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (connect==true)
        {
            //si le mdp est correct, on passe en phase de vote
            
       try
       {//tant que le programme tourne
           while (relai.getRunning())
           {//on recupere le vote
               int vote=m_Input.read();
               String votes = Integer.toString(vote);
               for (int i = 0; i< votes.length();i++)
               { //on renvoit le vote
               relai.relayVote(Integer.getInteger(Character.toString(votes.charAt(i))));
               };
               try {
                   //on endort le thread, qui sera reveillé a la prochaine question
                    relai.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(threadConnection.class.getName()).log(Level.SEVERE, null, ex);
                }
               //on envoie le message de déblocage
             m_Output.write(relai.getNbRep());
           }
       }
       catch (IOException e)
       {
             System.err.println(e);
       }
    
    }
        else try {
            //sinon on averti que le mot de passe est mauvais
            relai.relayVote(2);
        } catch (IOException ex) {
            Logger.getLogger(threadConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
